package simulation;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import agents.Action;
import agents.Agent;
import agents.Ant;
import agents.Environment;
import agents.task.TaskAgent;
import domain.Clock;

public class Simulation {
	
	public Simulation(AgentProvider newAgentProvider) {
		this.agentManager = new AgentManager();
		this.agentProvider = newAgentProvider;
	}
	
	private AgentManager agentManager;
	
	public AgentManager getAgentManager(){
		return agentManager;
	}

	//doe een stap in de simulatie (=> ga één tijdseenheid verder)
	public void doSimulationStep() {
		
		addNewAgents();
		removeAgents();
		
		for(Agent agent : getAgents()) {
			agent.think();
		}
		boolean done = false;
		while(!done) {
			done = true;
			List<Ant> ants = new ArrayList<Ant>();
			for(Agent agent : getAgents()) {
				ants.addAll(agent.getAnts());
			}
			for(Ant ant : ants) {
				executeAnt(ant);
			}
			done = (ants.size() == 0);
		}
		//decision
		List<Action> actions = new ArrayList<Action>();
		for(TaskAgent taskAgent : agentManager.getAllTaskAgents()) {
			Action a = taskAgent.getAction();
			if (a!=null) actions.add(a);
		}
				
		getEnvironment().react(actions);
		
		removeCompletedTasks();
		
		Clock.getInstance().increaseTime();		
	}

	private void removeCompletedTasks() {
		for(TaskAgent ta : agentManager.getAllTaskAgents()) {
			if(ta.isCompleted()) {
				agentManager.removeTaskAgent(ta);
			}
		}
	}

	private void addNewAgents() {
		Collection<Agent> newAgents = agentProvider.getNewAgents();
		getEnvironment().addAllAgents(newAgents);
		agentManager.addAllAgents(newAgents);	
	}
	
	private void removeAgents() {
		Collection<Agent> agentsToRemove = agentProvider.getAgentsToRemove();
		getEnvironment().removeAgents(agentsToRemove);
		agentManager.removeAgents(agentsToRemove);	
	}
	
	public interface AgentProvider {
		public Collection<Agent> getNewAgents();
		public Collection<Agent> getAgentsToRemove();
	}

	private AgentProvider agentProvider;

	//depth first worden per ant kinderen afgegaan
	private void executeAnt(Ant ant) {
		List<Ant> childAnts = new ArrayList<Ant>();
		while(!ant.isTerminated()) {
			ant.doStep();
			childAnts.addAll(ant.getChildAnts());
		}
		
		for(Ant childAnt : childAnts) {
			executeAnt(childAnt);
		}
	}

	private Collection<Agent> getAgents() {
		return agentManager.getAllAgents();
	}
	
	private Environment getEnvironment() {
		return Environment.getInstance();
	}

}
